
class MyPackage:
    def __init__(self, receiverIndex):
        self.index = receiverIndex
        self.data = []
        self.ports = {}
        self.port = 0
        self.len = 0
        self.len_cur = 0
        self.checkSum = 0
        self.state = 0
        
    def scan(self, byteStream):
        for rx in byteStream:
            if self.state == 0:
                if rx == 0x7f:
                    self.state = 1
            elif self.state == 1:
                if rx & 0x0f == self.index:
                    self.port = rx >> 4
                    self.state = 2
                else:
                    self.state = 0
            elif self.state == 2:
                self.len = rx
                self.data = []
                self.len_cur = 0
                self.state = 3
                self.checkSum = 0
            elif self.state == 3:
                if self.len_cur < self.len:
                    self.data.append(rx)
                    self.checkSum += rx
                    self.len_cur += 1
                else:
                    #if rx == self.checkSum % 256:
                    if rx == 0x7e:
                        portFunc = self.ports.get(self.port)
                        if portFunc != None:
                            portFunc(self.data)
                    self.state = 0
    def put(self, index, port, data):
        datalen = len(data)        
        checksum=sum(data) % 256
        #data_s = bytes([0x7f, index + port * 16, datalen]) + bytes(data) + bytes([checksum])
        data_s = bytes([0x7f, index + port * 16, datalen]) + bytes(data) + bytes([0x7e])
        return data_s
    
    def setListener(self, port, callBackFunc):
        self.ports[port] = callBackFunc
        
'''
def func(x):
    print(x)
    
if __name__=='__main__':

    pk = MyPackage(1)
    pk.setListener(2,func)
    a=b'\xfd\xff\xfafsvfcdscdsdc\x7f\x21\x03\xfe\xfd\xff\xfa\x21\x03\xfe\xfd\xff\xfa'
    pk.scan(a)
    pk.scan(pk.put(1,2,[12,45,34,23,8]))
'''
